<!--
 * @FileDescription 实训
 * @Author lz
 * @Date 20230131 13:55:37
 * @LastEditors lz
 * @LastEditTime 20230131 13:55:37
-->
<template>
  <div class="wp">
    <!-- 顶部 -->
    <hdrModel Hierarchy="2" :ID="newArr.get(state.StoragePath)"></hdrModel>
    <div class="times" v-if="HomeContent.Default.ApplicationType.value == '考核'">
      {{ TM(state.times) }}
    </div>
    <div
      class="Btn"
      @click="submit()"
      v-if="HomeContent.Default.ApplicationType.value == '考核'"
    >
      提交
    </div>
    <!-- 列表 -->
    <div class="Sidebar" v-if="state.showHide">
      <div class="putAway" @click="show()"></div>
      <div class="ListOptions">
        <div class="statistics">
          <img src="/structure/list_sign_select.png" />
          实训项目( {{ state.AnsweredNum }}/{{
            simulationData.Default.trainingDatalist.value.length
          }})
        </div>
        <div
          class="optionList"
          v-for="(item, index) in simulationData.Default.trainingDatalist.value"
          :key="index"
          @click="selectBtn(item, index)"
          :class="item.state == 2 ? 'ChickOut' : ''"
        >
          {{ item.Name + item.Type }}
          <img src="/structure/Checkmark.png" v-if="item.IsSubmit" />
        </div>
      </div>
    </div>
    <div class="SidebarHide" v-if="!state.showHide">
      <div class="openBar" @click="show()"></div>
    </div>

    <judge
      @doSth="showTips"
      v-if="state.topicType == '结构'"
      :Answer="simulationData.Default.trainingDatalist.value[state.choiceIndex].Answer"
      :Questions="
        simulationData.Default.trainingDatalist.value[state.choiceIndex].Questions
      "
    >
    </judge>

    <theBlanks @doSth="showTips" v-if="state.topicType == '参数'"></theBlanks>

    <principle
      @doSth="showTips"
      v-if="state.topicType == '原理'"
      :Answer="simulationData.Default.trainingDatalist.value[state.choiceIndex].Answer"
      :Questions="
        simulationData.Default.trainingDatalist.value[state.choiceIndex].Questions
      "
      :Dialogues="
        simulationData.Default.trainingDatalist.value[state.choiceIndex].Dialogues
      "
    ></principle>

    <choice ref="choiceRef" @doSth="showTips" v-if="state.topicType == '组成'"></choice>

    <promptBox ref="childRef"></promptBox>

    <subpro ref="subproRef"></subpro>

    <strMessageBox
      ref="messageBoxRef"
      :Questions="state.Questions"
      :messageType="state.messageType"
      :ID="newArr.get(state.StoragePath)"
    ></strMessageBox>

    <Speak hidden ref="audioRef" :stats="HomeContent.Default.pausableType.value">
      {{ state.VoiceValue }}
    </Speak>
  </div>
</template>

<script setup lang="ts">
import Speak from "@components/TTS/Speak.vue";

import hdrModel from "../strHeader/index.vue";
import judge from "./model/judge.vue";
import choice from "./model/choice.vue";
import theBlanks from "./model/theBlanks.vue";
import promptBox from "./model/promptBox.vue";
import principle from "./model/principle.vue";
import subpro from "./model/subpro.vue";
import simulationData from "../simulationTraining/simulationTraining";

import {
  reactive,
  ref,
  toRefs,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onUnmounted,
  StyleValue,
  defineProps,
  defineEmits,
  watch,
} from "vue";
import OrbitCameraComponent from "@components/Apps/InertialNavigation/OrbitCameraComponent";
import { ClientMessage } from "@runtime/generate/message/ClientMessage";
import WebSocketComponent from "@runtime/module/WebSocket/WebSocketComponent";
import AnimatorComponent from "@runtime/UnityEngineBridge/AnimatorComponent";
import AssetLoaderComponent from "@runtime/UnityEngineBridge/AssetLoaderComponent";
import GameObjectComponent from "@runtime/UnityEngineBridge/GameObjectComponent";
import LabelComponent from "@runtime/UnityEngineBridge/LabelComponent";
import MessageCode from "../MessageCode";
import HomeContent from "../HomeContent";
import strMessageBox from "../strMessageBox.vue";
import HighlighterComponent from "@runtime/UnityEngineBridge/HighlighterComponent";

const state = reactive({
  showHide: true,
  optionList: [
    {
      name: "1.xxx组成",
      types: 2,
      state: 1,
    },
    {
      name: "2.xxx组成",
      types: 1,
      state: 1,
    },
    {
      name: "3.xxx组成",
      types: 1,
      state: 1,
    },
  ],
  topicType: "",
  StoragePath: "",
  Answered: 0,
  choiceIndex: -1,
  AnsweredNum: 0,
  times: 0, //用时毫秒数
  timer: 0, // 定时器对象
  Questions: "",
  messageType: 0,
  VoiceValue: "",
});

// 已加载模型数组
let newArr = ref(new Map());
let Id: number = 0;
let PerD: any = {};

const audioRef = ref();
async function selectBtn(val: any, index: number) {
  // 每切换一次，结束播放应该都为false
  HomeContent.Default.endplay.value.ended = false;
  // 判断如果暂停播放为真，切换后就依旧暂停
  if (HomeContent.Default.pausableType.value.pausable) {
    // 切换重新加载audio
    audioRef.value.replay();
    HomeContent.Default.pausableType.value.pausable = true;   
  } else { 
    audioRef.value.replay();
  }

  //清除旋转
  // WebSocketComponent.Default.PostMessage(new ClientMessage.OrbiiCameraAutoObservationMessage())

  if (index == state.choiceIndex) {
    return;
  }

  // 清除高亮
  await HighlighterComponent.Default.ClearAsync();

  LabelComponent.Default.Clear();
  state.choiceIndex = index;
  simulationData.Default.subscript.value = index;
  if (state.StoragePath != "") {
    // 隐藏模型
    await GameObjectComponent.Default.HideAsync(newArr.value.get(state.StoragePath));
  }

  if (newArr.value.get(val.Asset) == undefined) {
    //首次加载
    Id = await AssetLoaderComponent.Default.LoadAsync(val.Asset);
    // 视角
    const PerspectiveData: ClientMessage.StructureAdapterResponse = await WebSocketComponent.Default.PostMessageAsync(
      new ClientMessage.StructureAdapterRequest(
        MessageCode.Default.MsgCodesList.VIEW_DATA_CONFIG,
        val.Asset + val.Type
      )
    );
    PerD = JSON.parse(PerspectiveData.Content).Result;
    await OrbitCameraComponent.Default.UpdateV2Async(
      PerD.TargetContainer,
      PerD.Horizontal,
      PerD.Vertical,
      PerD.Distance,
      PerD.MinDistance,
      PerD.MaxDistance,
      PerD.RotateSensitivity,
      PerD.RotateSensitivity,
      PerD.ScrollSensitivity
    );
    // 储存键值对
    newArr.value.set(val.Asset, Id);
    state.StoragePath = val.Asset;
    // 模型动画
    if (val.Type == "组成" || val.Type == "原理") {
      await AnimatorComponent.Default.PlayAsync(Id, "Default", 2000);
    }
    if (val.Type == "组成" || val.Type == "参数") {
      // 标签方法
      await LabelComponent.Default.LoadAsync(newArr.value.get(val.Asset));
    }
  } else {
    // console.log('已加载')
    // 显示模型
    await GameObjectComponent.Default.ShowAsync(newArr.value.get(val.Asset));
    // 视角
    const PerspectiveData: ClientMessage.StructureAdapterResponse = await WebSocketComponent.Default.PostMessageAsync(
      new ClientMessage.StructureAdapterRequest(
        MessageCode.Default.MsgCodesList.VIEW_DATA_CONFIG,
        val.Asset + val.Type
      )
    );
    PerD = JSON.parse(PerspectiveData.Content).Result;
    await OrbitCameraComponent.Default.UpdateV2Async(
      PerD.TargetContainer,
      PerD.Horizontal,
      PerD.Vertical,
      PerD.Distance,
      PerD.MinDistance,
      PerD.MaxDistance,
      PerD.RotateSensitivity,
      PerD.RotateSensitivity,
      PerD.ScrollSensitivity
    );
    // 储存键值对
    state.StoragePath = val.Asset;
    // 模型动画
    if (val.Type == "组成" || val.Type == "原理") {
      await AnimatorComponent.Default.PlayAsync(
        newArr.value.get(val.Asset),
        "Default",
        2000
      );
    }
    if (val.Type == "组成" || val.Type == "参数") {
      // 标签方法
      await LabelComponent.Default.LoadAsync(newArr.value.get(val.Asset));
    }
  }
  state.topicType = val.Type;
  simulationData.Default.trainingDatalist.value.forEach((i) => {
    if (i.Name + i.Type == val.Name + val.Type) {
      i.state = 2;
    } else {
      i.state = 1;
    }
  });

  if (val.Type == "结构") {
    state.VoiceValue =
      simulationData.Default.trainingDatalist.value[state.choiceIndex].Questions;
  } else if (val.Type == "组成") {
    state.VoiceValue = "请将下列名称拖入到对应的部件框里";
  } else if (val.Type == "参数") {
    state.VoiceValue = "请将该部件的参数信息补充完整";
  } else if (val.Type == "原理") {
    state.VoiceValue = "请根据技师A和技师B的描述，做出正确判断";
  }
}
function show() {
  state.showHide = !state.showHide;
}
const childRef = ref<any>();
const subproRef = ref<any>();
const messageBoxRef = ref<any>();

async function showTips(val: boolean) {
  if (HomeContent.Default.ApplicationType.value == "训练") {
    // 训练模式
    childRef.value.show(val);
    state.AnsweredNum = 0;
    if (val == true) {
      simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = true;
      simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit = true;
    } else if (val == false) {
      simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = false;
      simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit = false;
    }
    simulationData.Default.trainingDatalist.value.forEach((item) => {
      if (item.IsSubmit) {
        state.AnsweredNum++;
      }
      if (state.AnsweredNum == simulationData.Default.trainingDatalist.value.length) {
        setTimeout(() => {
          state.Questions = "训练完成是否返回考核设置页！";
          state.messageType = 1;
          messageBoxRef.value.showModel();
        }, 1000);
      }
    });
  } else if (HomeContent.Default.ApplicationType.value == "考核") {
    subproRef.value.show();
    // 考核模式
    state.AnsweredNum = 0;
    if (val == true) {
      simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = true;
    } else if (val == false) {
      simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight = false;
    }
    simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit = true;
    simulationData.Default.trainingDatalist.value.forEach((item) => {
      if (item.IsSubmit) {
        state.AnsweredNum++;
      }
    });
    let newData = {
      IsRight: simulationData.Default.trainingDatalist.value[state.choiceIndex].IsRight,
      IsSubmit: simulationData.Default.trainingDatalist.value[state.choiceIndex].IsSubmit,
      Id: simulationData.Default.trainingDatalist.value[state.choiceIndex]._id,
    };
    await WebSocketComponent.Default.PostMessageAsync(
      new ClientMessage.StructureAdapterRequest(
        MessageCode.Default.MsgCodesList.APPRAISE_SUBMIT_CURRENT_TASK,
        JSON.stringify(newData)
      )
    );
  }
}
//提交
function submit() {
  let tim = state.times / 1000;
  state.messageType = 2;
  state.Questions = "是否提交考核！";
  messageBoxRef.value.showModel(tim);
}
//时间转
function TM(ms: number) {
  let h: string | number = Math.floor(ms / 1000 / 60 / 60);
  let m: string | number = Math.floor(ms / 1000 / 60);
  let s: string | number = Math.floor(ms / 1000);

  if (h === 1) {
    // 当时间刚好是60分钟时，让它以mm:ss格式显示,即显示60:00,而不是显示01:00:00
    if (m / 60 === 1 && s % 60 === 0) {
      h = "";
      m = "60:";
    } else {
      h = "01:";
      m = addZero(m % 60) + ":";
    }
    s = addZero(s % 60);
  } else {
    h = h === 0 ? "" : addZero(h) + ":";
    m = addZero(m % 60) + ":";
    s = addZero(s % 60);
  }
  return h + m + s;
}
// 进行补0操作
function addZero(n: string | number) {
  return n < 10 ? "0" + n : n;
}
onMounted(() => {
  simulationData.Default.trainingDatalist.value.forEach((i) => {
    i.state = 1;
  });
  // 60s倒计时
  state.timer = window.setInterval(() => {
    state.times += 1000;
    if (state.times == 3600000) {
      clearInterval(state.timer);
      state.timer = 0;
    }
  }, 1000);
  //首次加载调用点击方法
  HomeContent.Default.pausableType.value.pausable = false
  selectBtn(simulationData.Default.trainingDatalist.value[0], 0);
});
</script>

<style scoped>
.wp {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  position: relative;
}

.Sidebar {
  position: absolute;
  top: 161px;
  left: -6px;
  width: 300px;
  height: 771px;
  background-image: url("/structure/MenuBorder_bg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.SidebarHide {
  position: absolute;
  top: 0;
  left: 0;
  width: 60px;
  height: 1044px;
}

.putAway {
  position: absolute;
  top: 350px;
  right: -50px;
  width: 66px;
  height: 81px;
  background-image: url("/structure/collapseArrow.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.openBar {
  position: absolute;
  top: 500px;
  right: 0px;
  width: 66px;
  height: 81px;
  background-image: url("/structure/collapseArrowHide.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
}

.ListOptions {
  width: 280px;
  height: 691px;
  margin-top: 46px;
  overflow-y: auto;
}

.ListOptions::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 6px;
  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}

.ListOptions::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/

  border-radius: 10px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #45b5ff;
}

.ListOptions::-webkit-scrollbar-track {
  /*滚动条里面轨道*/

  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background: #123965;
}

.statistics {
  width: 250px;
  height: 54px;
  display: inline-block;
  vertical-align: middle;
  font-size: 18px;
  font-weight: bold;
  color: #ffffff;
  background: linear-gradient(
    90deg,
    RGBA(10, 43, 87, 0.1),
    RGBA(7, 77, 129, 1),
    RGBA(10, 43, 87, 0.1)
  );
}

.statistics > img {
  width: 54px;
}

.optionList {
  height: 60px;
  width: 230px;
  margin-left: 24px;
  border-bottom: 1px solid RGBA(255, 255, 255, 0.1);
  font-size: 16px;
  font-weight: 400;
  color: #b1d0f4;
  display: inline-block;
  vertical-align: middle;
  line-height: 60px;
  padding-left: 30px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  position: relative;
}

.optionList > img {
  margin-left: 40px;
  width: 26px;
  position: absolute;
  right: 1px;
  top: 16px;
}

.ChickOut {
  padding-left: 20px;
  color: #1890ff;
}

.Btn {
  position: absolute;
  left: 76%;
  top: 16px;
  z-index: 999;
  font-size: 18px;
  text-align: center;
  color: #fff;
  font-weight: bold;
  line-height: 54px;
  width: 120px;
  height: 54px;
  background-image: url("/structure/btn_bg.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  margin-top: -7px;
  margin-right: 10px;
}

.Btn:hover {
  color: #fff;
  background-image: url("/structure/btn_bg_select.png");
}

.times {
  position: absolute;
  left: 72%;
  top: 18px;
  float: left;
  line-height: 36px;
  font-size: 24px;
  font-weight: bold;
  color: #fff;
  margin-right: 10px;
}
</style>
